<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入商品名称"
            v-model="paramsInfo.query"
            clearable
            @clear="getGoodsList"
          >
            <el-button slot="append" icon="el-icon-search" @click="searchGoods"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddGood">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table :data="GoodsList" style="width: 100%" border stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="goods_name" label="商品名称" width="800px"></el-table-column>
        <el-table-column prop="goods_price" label="商品价格(元)" width="195px"></el-table-column>
        <el-table-column prop="goods_weight" label="商品重量" width="170px"></el-table-column>
        <el-table-column prop="add_time" label="创建时间" width="140px">
          <template slot-scope="scope">{{scope.row.add_time | dateFormat}}</template>
        </el-table-column>
        <el-table-column label="操作" width="240px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteGood(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paramsInfo.pagenum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="paramsInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>
    </el-card>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑商品" :visible.sync="editDialogVisible" width="50%" @close="editCloseHandle">
      <div :class="'el-dialog-div'">
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="100px"
          label-position="top"
        >
          <el-tabs
            :tab-position="'left'"
            v-model="activeName"
            :before-leave="beforeTabsLeave"
            @tab-click="tabClick"
          >
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="editForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格(元)" prop="goods_price">
                <el-input v-model="editForm.goods_price" type="number" :min="0.1"></el-input>
              </el-form-item>
              <el-form-item label="商品数量(个)" prop="goods_number">
                <el-input v-model="editForm.goods_number" type="number" :min="1"></el-input>
              </el-form-item>
              <el-form-item label="商品重量(克)" prop="goods_weight">
                <el-input v-model="editForm.goods_weight" type="number" :min="1"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <el-cascader
                  v-model="editForm.goods_cat"
                  :options="cateList"
                  :props="CascaderProps"
                  @change="CascaderChange"
                  clearable
                ></el-cascader>
              </el-form-item>
            </el-tab-pane>

            <el-tab-pane label="商品参数" name="1">
              <el-form-item
                :label="item.attr_name"
                v-for=" item in manyTableData"
                :key="item.attr_id"
              >
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox :label="an" v-for="(an,i) in item.attr_vals" :key="i" border></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>

            <el-tab-pane label="商品属性" name="2">
              <el-form-item
                :label="item.attr_name"
                v-for=" item in onlyTableData"
                :key="item.attr_id"
              >
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>

            <el-tab-pane label="商品图片" name="3">
              <el-upload
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                list-type="picture"
                :headers="uploadHeaders"
                :on-success="uploadSuccess"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <quill-editor v-model="editForm.goods_introduce"></quill-editor>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCloseHandle">取 消</el-button>
        <el-button type="primary" @click="editGood">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="30%">
      <img :src="previewUrl" width="100%" />
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      activeName: "0",
      GoodsList: [],
      paramsInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },
      total: 0,
      editForm: {},
      editDialogVisible: false,
      editFormRules: {
        goods_name: [
          {
            required: true,
            message: "商品名称不能为空",
            trigger: "blur"
          }
        ],
        goods_price: [
          {
            required: true,
            message: "商品价格不能为空",
            trigger: "blur"
          }
        ],
        goods_weight: [
          {
            required: true,
            message: "商品重量不能为空",
            trigger: "blur"
          }
        ],
        goods_number: [
          {
            required: true,
            message: "商品数量不能为空",
            trigger: "blur"
          }
        ],
        goods_cat: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "blur"
          }
        ]
      },
      cateList: [],
      CascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      manyTableData: [],
      onlyTableData: [],
      uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload",
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem("token")
      },
      previewUrl: "",
      previewVisible: false,
      fileList: [],
      good_id: 0
    };
  },
  created() {
    this.getGoodsList();
    this.getCateList();
  },
  methods: {
    async getGoodsList() {
      const { data: res } = await this.$http.get("goods", {
        params: this.paramsInfo
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.GoodsList = res.data.goods;
        this.total = res.data.total;
        // console.log(this.GoodsList);
      }
    },
    handleSizeChange(newSize) {
      this.paramsInfo.pagesize = newSize;
      this.getGoodsList();
    },
    handleCurrentChange(newPage) {
      this.paramsInfo.pagenum = newPage;
      this.getGoodsList();
    },
    async deleteGood(row) {
      console.log(row);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该商品, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        const { data: res } = await this.$http.delete("goods/" + row.goods_id);
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg + "删除失败");
        } else {
          this.$message.success("商品" + row.goods_name + "已被删除成功!");
          this.getGoodsList();
        }
      }
    },
    searchGoods() {
      this.paramsInfo.pagenum = 1;
      this.paramsInfo.pagesize = 10;
      this.getGoodsList();
    },
    goAddGood() {
      this.$router.push("/goods/add");
    },
    async showEditDialog(row) {
      this.activeName = "0";
      this.goods_id = row.goods_id;
      const { data: res } = await this.$http.get("goods/" + this.goods_id);

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.editDialogVisible = true;
        this.editForm = res.data;
        this.editForm.goods_cat = this.editForm.goods_cat
          ? this.editForm.goods_cat.split(",")
          : [];
        this.editForm.goods_cat = this.editForm.goods_cat.map(item => {
          return +item;
        });
        this.fileList = this.editForm.pics;
        this.fileList.forEach(item => {
          item.url = item.pics_big_url;
        });
      }
    },
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.cateList = res.data;
      }
    },
    CascaderChange() {
      if (this.editForm.goods_cat.length !== 3) {
        this.editForm.goods_cat = [];
      } else {
      }
    },
    beforeTabsLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.editForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类！");
        return false;
      } else {
      }
    },
    //单击标签触发事件
    async tabClick() {
      if (this.activeName === "1" || this.activeName === "2") {
        let str = "";
        if (this.activeName === "1") {
          str = "many";
        } else {
          str = "only";
        }
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: str }
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        } else {
          if (this.activeName === "1") {
            res.data.forEach(item => {
              item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
            });
            this.manyTableData = res.data;
          } else {
            this.onlyTableData = res.data;
          }
        }
      } else {
      }
    },
    editCloseHandle() {
      this.editDialogVisible = false;
      this.$refs.editFormRef.resetFields();
      this.getGoodsList();
    },
    editGood() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("请填写必要的表单项！");
        } else {
          this.editForm.goods_cat = this.editForm.goods_cat.join(",");
          this.manyTableData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(",")
            };
            this.editForm.attrs.push(newInfo);
          });
          this.onlyTableData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            };
            this.editForm.attrs.push(newInfo);
          });
          const { data: res } = await this.$http.put(
            `goods/${this.goods_id}`,
            this.editForm
          );
          console.log(res);

          if (res.meta.status !== 200) {
            this.editForm.goods_cat = this.editForm.goods_cat
              ? this.editForm.goods_cat.split(",")
              : [];
            return this.$message.error(res.meta.msg);
          } else {
            this.$message.success("商品信息修改成功！");
            this.editDialogVisible = false;
          }
        }
      });
    },
    //单击图片触发事件
    handlePreview(file) {
      this.previewUrl = file.response.data.url;
      this.previewVisible = true;
    },
    //点击移除图片触发事件
    handleRemove(file) {
      const filePath = file.response.data.tmp_path;
      const i = this.editForm.pics.findIndex(x => {
        x.pic = filePath;
      });
      this.editForm.pics.splice(i, 1);
    },
    //上传图片成功触发事件
    uploadSuccess(res) {
      const picUrl = { pic: res.data.tmp_path };
      this.editForm.pics.push(picUrl);
    }
  },

  computed: {
    cateId() {
      if (this.editForm.goods_cat.length !== 3) {
        return null;
      } else {
        return this.editForm.goods_cat[2];
      }
    }
  }
};
</script>
<style lang="less" scoped>
.el-dialog-div {
  height: 60vh;
  overflow: auto;
}

.el-checkbox {
  margin: 0 10px 0 0 !important;
}
</style>
